#encoding=utf8
'''
Created on Oct 29, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple

from core.widgets import CustomTextarea, CustomCheckboxSelectMultiple
from ads_info.models import AdsInfo, UnitType, CROSS_PROMO_NETWORK_NAME,\
    CrossPromoReq, CrossPromoTokenName, CrossPromoToken


class AdsInfoForm(forms.ModelForm):

    error_messages = {'required': 'This field is required.'}

    cross_promo_ads = forms.ModelMultipleChoiceField(required=False,
        widget=CustomCheckboxSelectMultiple,
        queryset=UnitType.objects.filter(network__name=CROSS_PROMO_NETWORK_NAME))
    cross_local = forms.CharField(required=False, max_length=1000,
        label=u'Cross Promo Creatives (Local)', widget=CustomTextarea)
    cross_remote = forms.CharField(required=False, max_length=1000,
        label=u'Cross Promo Creatives (Dropbox)', widget=CustomTextarea)
    note = forms.CharField(required=False, widget=CustomTextarea(
        attrs={'rows': '5', 'style': '''overflow: hidden;
        word-wrap: break-word; resize: none; width: 400px; height: 46px;'''}),
        label=u'Other Ad Network / Notes')

    units = forms.ModelMultipleChoiceField(required=True,
        queryset=UnitType.objects.exclude(network__name=CROSS_PROMO_NETWORK_NAME).\
            filter(network__status='D'),
        widget=FilteredSelectMultiple('Units', False, {"style": "height: 200px;"}))

    class Meta:
        model = AdsInfo

    def __init__(self, *args, **kwargs):
        super(AdsInfoForm, self).__init__(*args, **kwargs)
        ids = [u.unit_id for u in self.instance.adsunit_set.all()]
        self.fields['units'].initial = UnitType.objects.filter(id__in=ids)
        if self.instance and self.instance.pk:
            self.fields['units'].required = False

    def clean_cross_promo_ads(self):
        cross_promo = self.cleaned_data.get('cross_promo')
        cross_promo_ads = self.cleaned_data.get('cross_promo_ads')
        if cross_promo == 'Y':
            if not cross_promo_ads:
                raise forms.ValidationError(self.error_messages['required'])
            return cross_promo_ads
        return ''

    def clean_cross_local(self):
        cross_promo = self.cleaned_data.get('cross_promo')
        cross_local = self.cleaned_data.get('cross_local')
        if cross_promo == 'Y':
            if not cross_local:
                raise forms.ValidationError(self.error_messages['required'])
            return cross_local
        return ''

    def clean_cross_remote(self):
        cross_promo = self.cleaned_data.get('cross_promo')
        cross_remote = self.cleaned_data.get('cross_remote')
        if cross_promo == 'Y':
            if not cross_remote:
                raise forms.ValidationError(self.error_messages['required'])
            return cross_remote
        return ''

    def clean_units(self):
        self.instance.units = self.cleaned_data.get('units')
        return self.cleaned_data.get('units')


class CrossPromoReqForm(forms.ModelForm):

    cross_local = forms.CharField(required=True, max_length=1000,
                                  label='Cross Promo Creatives (Local)',
                                  widget=CustomTextarea)
    cross_remote = forms.CharField(required=True, max_length=1000,
                                   label='Cross Promo Creatives (Dropbox)',
                                   widget=CustomTextarea)
    notes = forms.CharField(required=False, widget=CustomTextarea(
        attrs={'rows': '5', 'style': '''overflow: hidden;
        word-wrap: break-word; resize: none; width: 400px; height: 46px;'''}),
        label='Notes')
    token = forms\
        .ModelMultipleChoiceField(required=True,
                                  queryset=CrossPromoTokenName.objects
                                  .filter(vendor__status='D'),
                                  widget=FilteredSelectMultiple('Tokens', False,
                                                                {"style": "height: 200px;"}))

    class Meta:
        model = CrossPromoReq

    def __init__(self, *args, **kwargs):
        super(CrossPromoReqForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['cross_local'].required = False
            self.fields['cross_remote'].required = False
            self.fields['token'].required = False

    def clean_token(self):
        tokens = self.cleaned_data.get('token')
        vendors = [unicode(t.vendor) for t in tokens]
        token_names = [t.name for t in tokens]
        if 'Chartboost' in vendors:
            if 'ID' in token_names:
                if 'Signature' not in token_names:
                    raise forms.ValidationError('Choose Chartboost - Signature too')
            if 'Signature' in token_names:
                if 'ID' not in token_names:
                    raise forms.ValidationError('Choose Chartboost - ID too')
        return tokens


class CrossPromoTokenForm(forms.ModelForm):

    value = forms.CharField(required=False, label='Token Value',
                            widget=CustomTextarea(attrs={
                                'style': '''overflow: hidden; \
                                            word-wrap: break-word; \
                                            resize: none; \
                                            width: 400px; \
                                            height: 20px;'''}))

    class Meta:
        model = CrossPromoToken
